package com.kingyea.mobilepolice.marketorg.service.impl;

import com.google.common.collect.Lists;
import com.kingyea.mobilepolice.marketorg.bean.MarketOrg;
import com.kingyea.mobilepolice.marketorg.bean.MarketOrgPo;
import com.kingyea.mobilepolice.marketorg.dao.MarketOrgMapper;
import com.kingyea.mobilepolice.marketorg.service.MarketOrgService;
import com.kingyea.mobilepolice.organization.bean.Organization;
import com.kingyea.mobilepolice.system.StateCode;
import com.kingyea.mobilepolice.util.Constants;
import com.kingyea.mobilepolice.util.ExceptionConditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Mr.Lin
 * @version v1.0.0
 * @description MarketOrg 实现类
 * @date Created in 2018-04-26 15:22:49
 */
@Service
@Transactional
public class MarketOrgServiceImpl implements MarketOrgService {

    private static final Logger LOGGER = LoggerFactory.getLogger(MarketOrgServiceImpl.class);

    @Resource
    private MarketOrgMapper marketOrgMapper;

    /**
     * 删除
     *
     * @param
     * @return
     */
    @Override
    public Boolean deleteMarketCode(Integer marketCode) {
        return marketOrgMapper.deleteMarketCode(marketCode) > 0;
    }

    /**
     * 保存
     *
     * @param marketOrg
     * @return
     */
    @Override
    public Boolean save(MarketOrg marketOrg) {
        return marketOrgMapper.save(marketOrg) > 0;
    }

    /**
     * 列表
     *
     * @param
     * @return
     */
    @Override
    public List<MarketOrg> search(Map<String, Object> map) {
        List<MarketOrg> list = marketOrgMapper.search(map);
        Map<String, String> marketOrgMap = list.stream().collect(Collectors.toMap(MarketOrg::getOrgSerialNo, MarketOrg::getOrgParentSerialNo));
        List<String> orgSerialNoList = Lists.newArrayList(marketOrgMap.keySet());
        // TODO get orgList
        List<Organization> orgList = Lists.newArrayList();

        return list;
    }

    @Transactional
    @Override
    public Boolean batchSave(MarketOrgPo po) {
        ExceptionConditions.checkNotNull(po, StateCode.NO_ARGUMENT_ERROR);
        ExceptionConditions.checkNotNull(po.getMarketOrgs(), StateCode.NO_ARGUMENT_ERROR);
        ExceptionConditions.checkNotNull(po.getMarketCode(), StateCode.NO_ARGUMENT_ERROR);
        marketOrgMapper.deleteMarketCode(po.getMarketCode());
        if (!po.getMarketOrgs().isEmpty()) {
            po.getMarketOrgs().forEach(bean -> bean.setOrgParentSerialNo(po.getMarketOrgs().stream().anyMatch(bean2 -> bean.getOrgSerialNo().equals(bean2.getOrgParentSerialNo())) ? bean.getOrgParentSerialNo() : Constants.TOP_LEVEL_ORGANIZATION));
            return marketOrgMapper.batchSave(po.getMarketOrgs()) == po.getMarketOrgs().size();
        }
        return Boolean.TRUE;
    }
}
